import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/common/chart_data.dart';
import 'package:safetymonitor/app/data/entities/application/device_histroy_data_entity.dart';
import 'package:safetymonitor/app/data/entities/application/env_company_tree_entity.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

///安全生产
class SafeProductionController extends GetxController {
  String startDate = '开始时间';
  String endDate = '结束时间';
  ///安全生产 公司数据
  List<EnvCompanyTreeEntity>? userEnvCompanyTreeEntity;

  //选中的安全 公司
  EnvCompanyTreeEntity? selectGs;

  //选系统
  List<EnvCompanyTreeChildren>? childrenXt;

  //选中的安全 系统
  EnvCompanyTreeChildren? _selectXt;

  //选类型  类型
  List<EnvCompanyTreeChildrenChildren>? childrenLX;

  //选中的安全 类型
  EnvCompanyTreeChildrenChildren? _selectLX;

  //选类型  设备
  List<EnvCompanyTreeChildrenChildrenChildren>? childrenSB;

  //选中的安全 设备
  EnvCompanyTreeChildrenChildrenChildren? _selectSB;

  //获取选中请求实体
  EnvCompanyTreeChildrenChildrenChildrenQueryParams? queryParams;

  // List<FlSpot> historyData = [];

  // final historyDataTimes = <String>[];

  Color _descColor(int i) {
    switch (i) {
      case 1:
        return Colors.red;
      case 2:
        return Colors.orange;
      case 3:
        return Colors.yellow;
      case 4:
        return Colors.blue;
      default:
        return Colors.red;
    }
  }

  String _descStr(int i) {
    switch (i) {
      case 1:
        return '红色报警';
      case 2:
        return '橙色报警';
      case 3:
        return '黄色报警';
      case 4:
        return '蓝色报警';
      default:
        return '红色报警';
    }
  }

  /// 选取
  void selectCompanyOn(String name) {
    if (name == '选企业') {
      if (userEnvCompanyTreeEntity?.length == 1) {
        return;
      }
      CustomEquipmentBottomSheet<EnvCompanyTreeEntity>(
        dataList: userEnvCompanyTreeEntity ?? [],
        checkedList: selectGs != null ? [selectGs!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            selectGs = value[0];
            //获取系统
            childrenXt = selectGs?.children;
            //选取后清空  系统 类型 设备选中数据
            _selectXt = null;
            _selectLX = null;
            _selectSB = null;

            childrenLX = [];
            childrenSB = [];
            //清除图标数据
            // historyData.clear();
            lineData.clear();
            update();
          }
        },
        title: '选企业',
        isMultiple: false,
      ).showBottomSheetDialog();
    } else if (name == '选系统') {
      CustomEquipmentBottomSheet<EnvCompanyTreeChildren>(
        dataList: childrenXt ?? [],
        checkedList: _selectXt != null ? [_selectXt!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            _selectXt = value[0];
            //获取类型
            childrenLX = _selectXt?.children;
            //选取后清空   类型 设备选中数据
            _selectLX = null;
            _selectSB = null;

            childrenSB = [];
            //清除图标数据
            // historyData.clear();
            lineData.clear();
            update();
          }
        },
        title: '选系统',
        isMultiple: false,
      ).showBottomSheetDialog();
    } else if (name == '选类型') {
      CustomEquipmentBottomSheet<EnvCompanyTreeChildrenChildren>(
        dataList: childrenLX ?? [],
        checkedList: _selectLX != null ? [_selectLX!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            _selectLX = value[0];
            //获取类型
            childrenSB = _selectLX?.children;
            //选取后清空  设备选中数据
            _selectSB = null;
            //清除图标数据
            // historyData.clear();
            lineData.clear();
            update();
          }
        },
        title: '选类型',
        isMultiple: false,
      ).showBottomSheetDialog();
    } else if (name == '选设备') {
      CustomEquipmentBottomSheet<EnvCompanyTreeChildrenChildrenChildren>(
        dataList: childrenSB ?? [],
        checkedList: _selectSB != null ? [_selectSB!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            _selectSB = value[0];
            //获取选中请求实体
            queryParams = _selectSB?.queryParams;
            //方法一调接口显示区域图
            // getLineChart();

            //方法二调接口显示区域图
            getNewLineChart();
          }
        },
        title: '选设备',
        isMultiple: false,
      ).showBottomSheetDialog();
    }
  }

  String getString({String name = ''}) {
    if (name == '选企业') {
      if (selectGs != null) {
        return selectGs!.getShowName().trim();
      }
    } else if (name == '选系统') {
      if (_selectXt != null) {
        return _selectXt!.getShowName().trim();
      }
    } else if (name == '选类型') {
      if (_selectLX != null) {
        return _selectLX!.getShowName().trim();
      }
    } else if (name == '选设备') {
      if (_selectSB != null) {
        return _selectSB!.getShowName().trim();
      }
    }
    return name;
  }

  // String name = '';

  // void getLineChart() async {
  //   final res = await HttpUtil()
  //       .generatePostRequest<GetDeviceHistoryDataEntity>(
  //         Interface.getDeviceHistoryData,
  //         data: queryParams?.toJson(),
  //       )
  //       .execute(isShowLoading: true, isShowToast: false);
  //   res.onSuccess((result) async {
  //     final data = result.data;
  //     if (data != null) {
  //       final points = data.points;
  //       if (points!.isEmpty) return;
  //       //x方向偏移量
  //       name = points[0].name ?? '';
  //       final charts = <FlSpot>[];
  //       historyDataTimes.clear();
  //       for (var idx = 0; idx < points[0].data!.length; idx++) {
  //         final item = points[0].data![idx];
  //         charts.add(FlSpot(idx.toDouble(), double.parse(item.value ?? '')));
  //         historyDataTimes.add(item.time ?? '');
  //       }
  //       historyData = charts;
  //       update();
  //     }
  //   });
  //   res.onError((result) {
  //     AppToast.showError(result.message, title: 'http：${result.code}');
  //   });
  // }

  /// 折线图数据
  List<CartesianSeries<PieData, String>> lineData = [];
  double? lineWidth, markerWidth, markerHeight;

  void getNewLineChart() async {
    if(queryParams == null){
      update();
      return;
    }
    queryParams?.queryStartTime=startDate=='开始时间'?null:startDate;
    queryParams?.queryEndTime=endDate=='结束时间'?null:endDate;
    lineData.clear();
    final res = await HttpUtil()
        .generatePostRequest<DeviceHistroyDataEntity>(
          Interface.getDeviceHistoryData,
          data: queryParams?.toJson(),
        )
        .execute(isShowLoading: true, isShowToast: false);
    res.onSuccess((result) async {
      final data = result.data;
      if (data != null) {
        final points = data.points;
        if (points.isEmpty) return  update();
        final List<PieData> linePlanNum = [];
        for (var idx = 0; idx < points[0].data.length; idx++) {
          linePlanNum.add(
            PieData(
              points[0].data[idx].time,
              double.parse(points[0].data[idx].value),
            ),
          );
        }

        //data.thresholdVals.notificationCategory 1阈值线线的上面有变颜色  3是阈值线线的下面变颜色
        //过滤alarmType==1的数据
        final alarmTypeFirstOneData = data.thresholdVals.where((element) =>element.alarmType==1).toList();
        //添加阈值线
        // for (var dat in data.thresholdVals) {
        for (var dat in alarmTypeFirstOneData) {
          lineData.add(
            SplineSeries<PieData, String>(
              dashArray: const <double>[5, 5],
              // 设置虚线样式
              dataSource: linePlanNum,
              xValueMapper: (PieData sales, _) => sales.xData,
              yValueMapper: (PieData sales, _) => dat.thresholdVal,
              name: _descStr(dat.alarmLevel),
              markerSettings: const MarkerSettings(isVisible: false),
              color: _descColor(dat.alarmLevel),
            ),
            // 阈值线系列
            // SplineAreaSeries<PieData, String>(
            //   dashArray: const <double>[5, 5],
            //   dataSource: linePlanNum,
            //   xValueMapper: (PieData data1, _) => data1.xData,
            //   yValueMapper: (PieData data1, _) =>dat.thresholdVal,
            //   // color: Colors.transparent, // 设置阈值线的颜色为透明
            //   gradient: const LinearGradient(
            //     begin: Alignment.topCenter,
            //     end: Alignment.bottomCenter,
            //     colors: [
            //       Colors.red,
            //       Colors.white,
            //     ],
            //   ),
            // ) ,
          );
        }
        //只添加1条线
        lineData.add(
          SplineSeries<PieData, String>(
            dataSource: linePlanNum,
            xValueMapper: (PieData sales, _) => sales.xData,
            yValueMapper: (PieData sales, _) => sales.yData,
            name: points[0].name,
            markerSettings: MarkerSettings(
              isVisible: true,
              height: markerWidth ?? 4,
              width: markerHeight ?? 4,
              shape: DataMarkerType.circle,
              borderWidth: 3,
              borderColor: Colors.cyan,
            ),
            color: Colors.cyan,
            dataLabelSettings: const DataLabelSettings(
              isVisible: true,
              labelAlignment: ChartDataLabelAlignment.auto,
            ),
            // pointColorMapper: (PieData data2, _) {
            //   if (data2.yData < data.thresholdVals[0].thresholdVal) {
            //     return Colors.yellow; // 小于的点为红色
            //   } else {
            //     return Colors.cyan; // 大于等于的点为绿色
            //   }
            // },
          ),
        );
        update();
      }
    });
    res.onError((result) {
      AppToast.showError(result.message, title: 'http：${result.code}');
    });
  }
}
